package cn.bonoon.kernel.web.handlers.loader;

import java.lang.reflect.Constructor;

import cn.bonoon.kernel.bytecode.QueryConverter;
import cn.bonoon.kernel.support.searcher.ISearcher;
import cn.bonoon.kernel.support.searcher.StandardFinder;

public final class StandardQueryParameterBuilder implements IQueryParameterBuilder{
	
	private final Class<?> queryClass;
	private Constructor<?> queryConstructor;
	private final ISearcher searcher;
	private final QueryConverter queryConverter;
	
	public StandardQueryParameterBuilder(Class<?> queryClass, ISearcher searcher) throws Exception{
		this.queryClass = queryClass;
		this.searcher = searcher;
		this.queryConverter = searcher.getQueryConverter(queryClass);
	}
	
	public ISearcher getSearcher() {
		return searcher;
	}
	
	public IQueryParameterBuilder init(){
		try{
			this.queryConstructor = queryClass.getConstructor();
		}catch(Exception ex){
			//无法使用查询条件
			return EMPTY;
		}
		return this;
	}

	@Override
	public Object instance() {
		try {
			return queryConstructor.newInstance();
		} catch (Exception e) {
			//nothing to do!
			return null;
		}
	}
	
	@Override
	public void query(StandardFinder finder, Object condition){
		queryConverter.query(finder.getAsmParser(), condition);
	}
}
